package com.atguigu.lease.web.admin.service.impl;

import com.atguigu.lease.common.exception.LeaseException;
import com.atguigu.lease.common.result.ResultCodeEnum;
import com.atguigu.lease.model.entity.*;
import com.atguigu.lease.model.enums.ItemType;
import com.atguigu.lease.web.admin.mapper.*;
import com.atguigu.lease.web.admin.service.*;
import com.atguigu.lease.web.admin.vo.apartment.ApartmentDetailVo;
import com.atguigu.lease.web.admin.vo.apartment.ApartmentItemVo;
import com.atguigu.lease.web.admin.vo.apartment.ApartmentQueryVo;
import com.atguigu.lease.web.admin.vo.apartment.ApartmentSubmitVo;
import com.atguigu.lease.web.admin.vo.fee.FeeValueVo;
import com.atguigu.lease.web.admin.vo.graph.GraphVo;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.checkerframework.checker.units.qual.A;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * @author liubo
 * @description 针对表【apartment_info(公寓信息表)】的数据库操作Service实现
 * @createDate 2023-07-24 15:48:00
 */
@Service
public class ApartmentInfoServiceImpl extends ServiceImpl<ApartmentInfoMapper, ApartmentInfo>
        implements ApartmentInfoService {


    // TODO: 2024/12/10 保存或更新公寓信息 
    @Autowired  //图片信息表
    private GraphInfoService graphInfoService; // 能调service优先调service，不调mapper
    @Autowired  //配套和公寓的中间表
    private ApartmentFacilityService apartmentFacilityService;
    @Autowired  //标签和公寓的中间表
    private ApartmentLabelService apartmentLabelService;
    @Autowired  //杂费和公寓的中间表
    private ApartmentFeeValueService apartmentFeeValueService;
    @Autowired  //省份信息表
    private ProvinceInfoService provinceInfoService;
    @Autowired  //市信息表
    private CityInfoService cityInfoService;
    @Autowired  //区域信息表
    private DistrictInfoService districtInfoService;

    @Autowired
    private RoomInfoService roomInfoService;
    // -------------------------------------------------------------------------------
    // TODO: 2024/12/10 根据条件分页查询公寓列表
    @Autowired
    private ApartmentInfoMapper apartmentInfoMapper;
    // -------------------------------------------------------------------------------
    // TODO: 2024/12/11 获取公寓详情
    @Autowired
    private FacilityInfoMapper facilityInfoMapper;
    @Autowired
    private LabelInfoMapper labelInfoMapper;
    @Autowired
    private FeeValueMapper feeValueMapper;
    @Autowired
    private GraphInfoMapper graphInfoMapper;

    /*
    // TODO: 2024/12/10  实现步骤:
           1. 接收整合数据Vo
           2. 判定是否是修改
           3. 调用公寓的保存或者更新
           4. 如果是更新,删除中间的四个表数据
           5. 最终一定进行中间表的数据的批量保存
        * */


    // TODO: 2024/12/10 保存或更新公寓信息
    @Override
    public void customSaveOrUpdate(ApartmentSubmitVo apartmentSubmitVo) {

        //定义一个布尔变量 isUpdate，用于表示当前操作是更新操作还是新增操作。
        //调用 apartmentSubmitVo 对象的 getId 方法，获取其 id 属性的值。
        // 如果 id 不为 null，则条件为 true；否则为 false。
        //如果 id 不为 null，则 isUpdate == true，表示这是一个更新操作。
        // 如果 id 为 null，则 isUpdate == false，表示这是一个新增操作
        boolean isUpdate = apartmentSubmitVo.getId() != null;

        //设置省市区的名称
        apartmentSubmitVo.setProvinceName(provinceInfoService.getById(apartmentSubmitVo.getProvinceId()).getName());
        apartmentSubmitVo.setCityName(cityInfoService.getById(apartmentSubmitVo.getCityId()).getName());
        apartmentSubmitVo.setDistrictName(districtInfoService.getById(apartmentSubmitVo.getDistrictId()).getName());


        // TODO: 2024/12/10
        //  调用公寓的 saveOrUpdate 方法，传入 apartmentSubmitVo 对象。
        saveOrUpdate(apartmentSubmitVo); //多态
        //TODO: 2024/12/10
        // 如果 isUpdate 为 true，表示这是一个【更新】操作，需要删除中间的四个表数据。
        if (isUpdate) {
            //1.图片表 【item_id 存的是公寓或者房间id + item_type == 公寓或者房间类型】
            LambdaQueryWrapper<GraphInfo> lambdaQueryWrapper = new LambdaQueryWrapper<>();
            lambdaQueryWrapper.eq(GraphInfo::getItemId, apartmentSubmitVo.getId());
            lambdaQueryWrapper.eq(GraphInfo::getItemType, ItemType.APARTMENT);
            graphInfoService.remove(lambdaQueryWrapper);

            //2.配套和公寓的中间表 只根据公寓id删除
            LambdaQueryWrapper<ApartmentFacility> apartmentFacilityLambdaQueryWrapper = new LambdaQueryWrapper<>();
            apartmentFacilityLambdaQueryWrapper.eq(ApartmentFacility::getApartmentId, apartmentSubmitVo.getId());
            apartmentFacilityService.remove(apartmentFacilityLambdaQueryWrapper);

            //3.标签和公寓的中间表
            LambdaQueryWrapper<ApartmentLabel> apartmentLabelLambdaQueryWrapper = new LambdaQueryWrapper<>();
            apartmentLabelLambdaQueryWrapper.eq(ApartmentLabel::getApartmentId, apartmentSubmitVo.getId());
            apartmentLabelService.remove(apartmentLabelLambdaQueryWrapper);

            //4.杂费和公寓的中间表
            LambdaQueryWrapper<ApartmentFeeValue> apartmentFeeValueLambdaQueryWrapper = new LambdaQueryWrapper<>();
            apartmentFeeValueLambdaQueryWrapper.eq(ApartmentFeeValue::getApartmentId, apartmentSubmitVo.getId());
            apartmentFeeValueService.remove(apartmentFeeValueLambdaQueryWrapper);
        }

        //TODO: 2024/12/10
        // 最终一定进行中间表的数据的批量保存
        //1. 图片信息
        List<GraphVo> graphVoList = apartmentSubmitVo.getGraphVoList();
        if (!CollectionUtils.isEmpty(graphVoList)) {
            ArrayList<GraphInfo> graphInfoList = new ArrayList<>(graphVoList.size());
            for (GraphVo graphVo : graphVoList) {
                GraphInfo graphInfo = new GraphInfo();
                graphInfo.setName(graphVo.getName());
                graphInfo.setUrl(graphVo.getUrl());
                graphInfo.setItemType(ItemType.APARTMENT);
                graphInfo.setItemId(apartmentSubmitVo.getId());
                graphInfoList.add(graphInfo);
            }
            graphInfoService.saveBatch(graphInfoList);
        }


        //2.公寓配套
        List<Long> facilityInfoIds = apartmentSubmitVo.getFacilityInfoIds();
        if (!CollectionUtils.isEmpty(facilityInfoIds)) {
            ArrayList<ApartmentFacility> apartmentFacilityList = new ArrayList<>(facilityInfoIds.size());
            for (Long facilityInfoId : facilityInfoIds) {
                ApartmentFacility apartmentFacility = ApartmentFacility.builder().facilityId(facilityInfoId).apartmentId(apartmentSubmitVo.getId()).build();
                apartmentFacilityList.add(apartmentFacility);
            }
            apartmentFacilityService.saveBatch(apartmentFacilityList);
        }
        //3.公寓标签
        List<Long> labelIds = apartmentSubmitVo.getLabelIds();
        if (!CollectionUtils.isEmpty(labelIds)) {
            ArrayList<ApartmentLabel> apartmentLabelList = new ArrayList<>(labelIds.size());
            for (Long labelId : labelIds) {
                ApartmentLabel apartmentLabel = ApartmentLabel.builder().labelId(labelId).apartmentId(apartmentSubmitVo.getId()).build();
                apartmentLabelList.add(apartmentLabel);
            }
            apartmentLabelService.saveBatch(apartmentLabelList);
        }

        //4. 公寓杂费值
        List<Long> feeValueIds = apartmentSubmitVo.getFeeValueIds();
        if (!CollectionUtils.isEmpty(feeValueIds)) {
            ArrayList<ApartmentFeeValue> apartmentFeeValueList = new ArrayList<>(feeValueIds.size());
            for (Long feeValueId : feeValueIds) {
                ApartmentFeeValue apartmentFeeValue = ApartmentFeeValue.builder().feeValueId(feeValueId).apartmentId(apartmentSubmitVo.getId()).build();
                apartmentFeeValueList.add(apartmentFeeValue);
            }
            apartmentFeeValueService.saveBatch(apartmentFeeValueList);
        }
    }

    // ---------------------------------------------------------------------------------------------------
    // TODO: 2024/12/10 根据条件分页查询公寓列表
    @Override
    public void customPage(Page<ApartmentItemVo> page, ApartmentQueryVo queryVo) {
        // 技巧：加上 “page = ” 到mapper层的参数中，就会自动把page对象传进去，不用再传了 “Page”<ApartmentItemVo>
        // 不加的 “page = ” 话 到mapper层的参数中，没有page对象，需要手动传 page对象。“Void”<ApartmentItemVo>
        // page = apartmentInfoMapper.customSelectPage(page, queryVo);
        apartmentInfoMapper.customSelectPage(page, queryVo);
    }

    // ---------------------------------------------------------------------------------------------------
    // TODO: 2024/12/10 根据id查询公寓详细信息
    /*        1. 先根据公寓id查询公寓详情对象
     *        2. 根据公寓id查询图片的vo对象 (定义mapper方法和mapper方法调用)
     *        3. 根据公寓id查询配套的对象  (定义mapper方法和mapper方法调用)
     *        4. 根据公寓id查询标签的对象  (定义mapper方法和mapper方法调用)
     *        5. 根据公寓id查询杂费的Vo对象 (定义mapper方法和mapper方法调用)
     *        6. 将数据合并到ApartmentDetailVo对象返回即可  */
    @Override
    public ApartmentDetailVo queryDetailById(Long id) {
        // 1. 先根据公寓id查询公寓详情对象
        ApartmentInfo apartmentInfo = getById(id);
        // 判断是否为空，如果查不到公寓信息返回空，就不用往下走了
        if (apartmentInfo == null) {
            return null;
        }
        // 2.根据公寓id查询图片的vo对象
        List<GraphVo> graphVoList = graphInfoMapper.queryByItemId(id, ItemType.APARTMENT);
        // 3.根据公寓id查询配套的对象（推荐直接调用配套的mapper，少了一层service的方法）
        //正常: 调用对方的service (事务的传播行为)
        //不正常: 1. service 只有一行 和 对应一个数据库动作 我们的service直接mapper依然能mapper加到当前事务
        //       2. 省一层代码结果  service xx -> mapper xx
        //        3. 有意避免循环注入的问题
        List<FacilityInfo> facilityInfoList = facilityInfoMapper.queryByApartmentId(id);

        // 4.根据公寓id查询标签的对象
        List<LabelInfo> labelInfoList = labelInfoMapper.queryByApartmentId(id);
        // 5.根据公寓id查询杂费的Vo对象
        List<FeeValueVo> feeValueVoList = feeValueMapper.queryByApartmentId(id);
        // 6.将数据合并到ApartmentDetailVo对象返回即可
        ApartmentDetailVo apartmentDetailVo = new ApartmentDetailVo();
        apartmentDetailVo.setGraphVoList(graphVoList);
        apartmentDetailVo.setFacilityInfoList(facilityInfoList);
        apartmentDetailVo.setLabelInfoList(labelInfoList);
        apartmentDetailVo.setFeeValueVoList(feeValueVoList);
        //新的api,可以进行属性赋值
        //进行相同属性的赋值
        //参数: 原数据
        //参数: 目标数据
        // TODO: 2024/12/11 将原对象的属性赋值给目标对象的相同属性！属性值迁移
        BeanUtils.copyProperties(apartmentInfo, apartmentDetailVo);
        return apartmentDetailVo;
    }

    // TODO: 2024/12/12 根据id删除公寓信息
    @Override //返回的是void
    public void customRemoveById(Long id) {
        //查询是否有公寓对应的房间
        LambdaQueryWrapper<RoomInfo> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(RoomInfo::getApartmentId,id);
        long count = roomInfoService.count(lambdaQueryWrapper);
        if (count > 0){  //方法1：return(极其不推荐按)
                        // 方法2：抛异常【推荐】配合springMVC全局异常处理器，最后到处理器对应的handler方法中来解决对应的问题
            //证明有房间  有重要子集 给与前端207
            //抛出异常,不会正常返回结果(业务正确), 使用全局异常处理器进行捕捉,返回对应的错误码给前端  DELETE_ERROR(207, "请先删除子集"),
            //不能继续执行了! 返回删除失败的提示
            // TODO: 2024/12/12 抛出异常 虽然RuntimeException可以放message，但是大家都抛RuntimeException，
            //  但是返回给前端的时候，不同的错误应该返回不同的code状态码，而RuntimeException没办法携带code
            //  前端无法区分，所以还是抛出异常，让全局异常处理器来处理，返回对应的错误码
            //  所以不能用RuntimeException
      //    throw new RuntimeException("message");
    // TODO: 2024/12/1
    //  方案1: 自定义各种类型的异常 例如: 删除公寓失败的异常  定义 账号错误异常/密码错误异常 ...  [不推荐]
    //  问题: 需要定义很多很多异常,很多很多的全局处理器,返回不同的状态码以及message
    //  方案2: 自定义通用异常,异常中可以(携带不同的业务错误状态码)code 和 message , 捕捉以后直接获取code message 装到 Result中 [推荐]
    //  只需定义一个异常 (带有 code 和 message )  || 也只需写一个处理器方法
            throw  new LeaseException(ResultCodeEnum.DELETE_ERROR);
        }


        /*
        * 当前ApartmentInfoServiceImpl实现类 继承了 ServiceImpl 泛型类，
          所以可以直接使用mybatis-puls提供的service层扩展方法
          根据id删除 用removeById方法
        * */
        //1.根据id删除公寓
        removeById(id);
// 删除中间表的数据 (图片表：是根据图片id和图片类型 item_type item_id)
//               (其它中间表：都是根据传过来的id值，与各个表中的公寓id【getApartmentId】相等就删除)
        //       [删除的是公寓对应的中间表，apartment_facility....]
// 【调用的是mybatis-plus提供的方法，不用考虑逻辑删除问题，用service层方法】
        //2.删除公寓相关的配套
        LambdaQueryWrapper<ApartmentFacility> apartmentFacilityLambdaQueryWrapper = new LambdaQueryWrapper<>();
        apartmentFacilityLambdaQueryWrapper.eq(ApartmentFacility::getApartmentId,id);
        apartmentFacilityService.remove(apartmentFacilityLambdaQueryWrapper);
        //3.删除公寓相关的标签
        LambdaQueryWrapper<ApartmentLabel> apartmentLabelLambdaQueryWrapper = new LambdaQueryWrapper<>();
        apartmentLabelLambdaQueryWrapper.eq(ApartmentLabel::getApartmentId,id);
        apartmentLabelService.remove(apartmentLabelLambdaQueryWrapper);
        //4.删除公寓相关的图片
        LambdaQueryWrapper<GraphInfo> graphInfoLambdaQueryWrapper = new LambdaQueryWrapper<>();
        graphInfoLambdaQueryWrapper.eq(GraphInfo::getItemType,ItemType.APARTMENT);
//GraphInfo::getItemId是一个方法引用，它指向GraphInfo类中的getItemId方法，id是一个变量，表示特定的公寓ID。
//传过来的id值，等于GraphInfo集合(graph_info表)中item_id列的值，如果item_type是APARTMENT，并且item_id等于传过来的id值，就删除
        graphInfoLambdaQueryWrapper.eq(GraphInfo::getItemId,id);
        graphInfoService.remove(graphInfoLambdaQueryWrapper);
        //5.删除公寓相关的杂费
        LambdaQueryWrapper<ApartmentFeeValue> apartmentFeeValueLambdaQueryWrapper = new LambdaQueryWrapper<>();
        apartmentFeeValueLambdaQueryWrapper.eq(ApartmentFeeValue::getApartmentId,id);
        apartmentFeeValueService.remove(apartmentFeeValueLambdaQueryWrapper);

    }
}




